<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class OwnserviceModelOwnservice extends JModel
{
	/**
	 * Owner transaction data
	 *
	 * @var object
	 */
	var $_data = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	*/
	function __construct() {
		parent::__construct();
	}

	/**
	 * Overridden get method to get properties owner transaction the data
	 *
	 * @access	public
	 * @param	string	$property	The name of the property
	 * @param	mixed	$value		The value of the property to set
	 * @return 	mixed 				The value of the property
	 * @since	1.0
	 */
	function get($property, $default=null) {
		/*
		* Load the Owner transaction data
		*/
		if(isset($this->_data->$property)) {
			return $this->_data->$property;
		}
		return $default;
	}
	
	/**
	 * Method get Transfer accounts
	 *
	 * @return object
	 * @since 1.5
	*/
	function getAccounts($id=0) {

		global $mainframe, $option;

		$user = & JFactory::getUser();

		$where = '';
		if($id) {
			if(is_array($id)) {
				$where = ' AND a.id IN ('.implode(',', $id).')';
			} else {
				$where = ' AND a.id ='.$id;
			}
		}

		$filter_order		= $mainframe->getUserStateFromRequest($option.'.ownservice.filter_order', 'filter_order', 'a.account_no', 'cmd');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest($option.'.ownservice.filter_order_Dir', 'filter_order_Dir', '', 'cmd');

		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		
		$query		= ' SELECT a.* FROM #__ownservice_accounts AS a '
					 .' LEFT JOIN #__ownservice_users AS p ON p.user_id = a.user_id '
					 .' LEFT JOIN #__users AS u ON u.id = a.user_id '
					 .' WHERE u.id='.$user->get('id')
					 .$where
					 .$orderby;

		$this->_db->setQuery($query);
		//echo $this->_db->_sql;
		$accounts = $this->_db->loadObjectList();

		return $accounts;
	}

	function getRate($id=0) {

		$user = & JFactory::getUser();

		$where='';

		if($id > 1) 
			$where = ' AND r.id='.$id;

		$query = ' SELECT r.*, c.code, c.sign, c.name, c.iscore FROM '
				.' #__ownservice_exchangerates AS r '
				.' LEFT JOIN #__ownservice_currencies AS c ON c.id=r.currency_id '
				.' LEFT JOIN #__ownservice_users AS u ON u.rate_id = r.id '
				.' WHERE u.user_id='.$user->get('id').' AND r.published = 1 '.$where;

		$this->_db->setQuery($query);
		$rate = $this->_db->loadObject();
		return $rate;
	}

	function getOwndata() {

		$user = & JFactory::getUser();

		$query = ' SELECT u.*, r.rate,c.code FROM #__ownservice_users AS u '
				.' LEFT JOIN #__ownservice_exchangerates AS r ON r.id=u.rate_id '
				.'LEFT JOIN #__ownservice_currencies AS c ON c.id=r.currency_id '
				.' WHERE u.user_id = '.$user->get('id');

		$this->_db->setQuery($query);
		$row = $this->_db->loadObject();

		return $row;
	}

	function store($data){

		//Check the request forgeries
		JRequest::checkToken() or jexit('Invalid Token');

		//Initialise variables
		$user			=& JFactory::getUser();
		$config		=& JFactory::getConfig();
		$tzoffset		= $config->getValue('config.offset');
		$nullDate		= $this->_db->getNullDate();

		$row = & $this->getTable( 'ownservice_customertransaction','' );

		if(!$row->bind($data)) {
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}

		// sanitise id field
		$row->id					= (int) $row->id;

		//get branch
		$branch					= $this->_getBranch($row->user_id);

		$row->branch_id		= $branch->id;

		// Are we saving from an item edit?
		// This code comes directly from the com_ownservice
		$row->created			= date('Y-m-d H:i:s');

		if ($row->created && strlen(trim( $row->created )) <= 10) {
			$row->created 	.= ' 00:00:00';
		}

		//total
		$row->total		= round((($row->amount * ($row->rate))- ($row->bankfee)), 2);

		//thai total
		$row->total_th	= round(($row->amount * $row->rate_th), 2);

		// Make sure the data is valid
		if (!$row->check()) {
			$this->setError($row->getError() );
			return false;
		}

		// Store it in the db
		if (!$row->store()) {
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}

		$this->_data = $row;

		return true;
	}

	/**
	 * Method get branch for transaction
	 *
	 *@access private
	 *@since 1.5
	*/
	function _getBranch($uid)
	{
		$query = ' SELECT branch_id '
				.' FROM #__ownservice_users '
				.' WHERE user_id='.$uid;
		
		$this->_db->setQuery($query);
		$branch_id =$this->_db->loadResult();

		if($branch_id)
		{
			$query = ' SELECT * '
					.' FROM #__ownservice_branches '
					.' WHERE id='.$branch_id;

			$this->_db->setQuery($query);
			$branch = $this->_db->loadObject();

			if(is_object($branch))
			{
				$branchname = $branch->name;

				if($branch->agent_id)
				{
					$query = ' SELECT * '
					.' FROM #__ownservice_branches '
					.' WHERE id='.$branch->agent_id;

					$this->_db->setQuery($query);
					$agent = $this->_db->loadObject();

					if(is_object($agent))
					{
						//$branchname = $agent->name;
						$branch = $agent;
					}
				}
			}
		}

		return $branch;
	}

	/**
	 * Method get invoice for transaction
	 *
	 *@access private
	 *@since 1.5
	*/
	function _getInvoice($branchid=0)
	{
		/*$date1 = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		$date2 = mktime(0, 0, 0, date('m'), date('d')+1, date('Y'));

		$where = ' WHERE ( created >= '
				.$this->_db->Quote(date('Y-m-d', $date1)." 04:00:00").' AND created <= '
				.$this->_db->Quote(date('Y-m-d', $date2)." 04:00:00").' )';

		if($branchid > 0)
		{
			$where .= ' AND branch_id='.$branchid;
		}
		$query = ' SELECT COUNT(*) FROM #__ownservice_transactions '
				.$where;

		$this->_db->setQuery($query);
		//echo $this->_db->_sql;
		$count	= $this->_db->loadResult();
		
		return $count;*/
		$date1 = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		$date2 = mktime(0, 0, 0, date('m'), date('d')+1, date('Y'));

		$where = ' WHERE ( created >= '
				.$this->_db->Quote(date('Y-m-d', $date1)." 04:00:00").' AND created <= '
				.$this->_db->Quote(date('Y-m-d', $date2)." 04:00:00").' )';

		$where .= ' AND branch_id='.$branchid;
		
		$query = ' SELECT MAX(transactionid) FROM #__ownservice_transactions '
				.$where;

		$this->_db->setQuery($query);
		$lastid	= $this->_db->loadResult();
		
		return $lastid;
	}

	/**
	 * Method to check expire archives
	 *
	 * @access public
	 * @since 1.5
	*/
	function canTransfer() {
		//Initialise variables
		$user		=& JFactory::getUser();
		$jnow		=& JFactory::getDate();
		$now		= $jnow->toMySQL();

		$query = ' SELECT p.* FROM #__ownservice_users AS p '
				.' LEFT JOIN #__users AS u ON u.id=p.user_id '
				.' WHERE p.user_id='.$user->get('id')
				.' AND deleted = 0 '
				.' AND expire_date >='.$this->_db->Quote($now);

		$this->_db->setQuery( $query );
		//echo $query;
		$row = $this->_db->loadObject();

		if(count($row) <= 0) {
			return false;
		}

		return true;
	}

	/**
	* Retrieval the account for user
	*/
	function getAccountDetail($account)
	{
		$db	= JFactory::getDBO();
		$user = JFactory::getUser();

		$query = 'SELECT * FROM #__ownservice_accounts WHERE account_no ='.$db->Quote($account).' AND user_id='.(int) $user->get('id');
		$db->setQuery($query);
		//echo $query;
		$row = $db->loadObject();

		return $row;
	}
}